//
//  MyJourneyMainViewModel.m
//  didihaha
//
//  Created by 赵忠鹏 on 2017/8/3.
//  Copyright © 2017年 zhaozhongpeng. All rights reserved.
//

#import "MyJourneyMainViewModel.h"
#import "MyJourneyMainModel.h"
#import "MyJourneyMainCell.h"

@interface MyJourneyMainViewModel ()

@property (nonatomic,strong)NSMutableArray *dataArr;

@end

@implementation MyJourneyMainViewModel




#pragma mark - 懒加载

- (NSMutableArray *)dataArr{
    if (_dataArr == nil) {
        _dataArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataArr;
}


- (void)refreshDataArr:(void (^)(NSArray *))block{
    // 读取数据
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"TAXI.txt"];
    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
        [self.dataArr removeAllObjects];
        

        NSString *content = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
        
        NSArray *tempDataArr = [[self jsonStringToKeyValues:content] objectForKey:@"Data"];
        
        
        [tempDataArr enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            MyJourneyMainModel *model = [[MyJourneyMainModel alloc] init];
            [model setValuesForKeysWithDictionary:obj];
            [self.dataArr addObject:model];
            
        }];
        
        if (block) {
            block(self.dataArr);
        }
    }else{
        // 没有文件 弹框
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"" message:@"Data Not Exist" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault  handler:^(UIAlertAction * action) {}];
    
        [alert addAction:defaultAction];
        [[UIViewController currentViewController] presentViewController:alert animated:YES completion:nil];
        
    }
    
    
}

//json字符串转化成OC键值对
- (id)jsonStringToKeyValues:(NSString *)JSONString {
    NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *responseJSON = nil;
    if (JSONData) {
        responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableContainers error:nil];
    }
    
    return responseJSON;
}



#pragma mark - 代理

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.dataArr.count - 1 >= indexPath.row) {
        MyJourneyMainModel *model = self.dataArr[indexPath.row];
        MyJourneyMainCell *cell = [MyJourneyMainCell cellWithTableView:tableView];
        cell.model = model;
        return cell;
    }else{
        return nil;
    }
    
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}


@end
